package mqigdcom.mqigd.netapi;

import mqigdcom.mqigd.CustomApp;
import mqigdcom.mqigd.db.RoadCondition;
import mqigdcom.mqigd.utils.LogUtils;
import mqigdcom.mqigd.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 网络接口的工具类
 */
public class NetApiExecutor {
    private static final String TAG = "NetApiExecutor";

    /**
     * 4.3.路况数据保存（Android、iOS）
     *
     * @param roadCondition 路况信息
     * @param callback      回调接口
     */
    public static void saveRoadCondition(RoadCondition roadCondition, Callback<ResponseBody> callback) {
        if (roadCondition != null) {
            try {
                Map<String, String> param = new HashMap<>();
                JSONObject data = new JSONObject();
                data.put("userid", roadCondition.getUserid());
                data.put("road_id", roadCondition.getRoad_id());
                data.put("unit_id", roadCondition.getUnit_id());

                // 根据采集分类，获取对应的病害名称和程度
                String type = roadCondition.getType();
                int y = roadCondition.getY();
                String strDssType = "";
                String strDssDegree = "";
                String[] arrDssType = Utils.getDssTypeByType(type);
                if (arrDssType != null && arrDssType.length - 1 >= y) {
                    String dssType = arrDssType[y];
                    String[] dssTypeSplit = dssType.split("-");
                    if (dssTypeSplit.length > 0) {
                        strDssType = dssTypeSplit[0];
                        if (dssTypeSplit.length > 1) {
                            strDssDegree = dssTypeSplit[1];
                        }
                    }
                }

                data.put("dss_type", strDssType);
                data.put("dss_degree", strDssDegree);
                data.put("length", roadCondition.getX() + "");
                data.put("value", roadCondition.getValue());
                data.put("line_dir", roadCondition.getLine_dir());
                data.put("start_stake", roadCondition.getStart_stake());
                data.put("end_stake", roadCondition.getEnd_stake());

                param.put("data", data.toString());
                Call<ResponseBody> call = null;
                if ("LQ".equals(type)) {
                    call = CustomApp.self.netApi.saveRoadConditionLQ(param);
                } else if ("SN".equals(type)) {
                    call = CustomApp.self.netApi.saveRoadConditionSN(param);
                } else if ("SCI".equals(type)) {
                    call = CustomApp.self.netApi.saveRoadConditionSCI(param);
                } else if ("TCI".equals(type)) {
                    call = CustomApp.self.netApi.saveRoadConditionTCI(param);
                } else if ("BCI".equals(type)) {
                    call = CustomApp.self.netApi.saveRoadConditionBCI(param);
                }
                if (call != null) {
                    printCallInfo(call);
                    call.enqueue(callback);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理网络接口的返回数据
     *
     * @param response 具体返回信息
     * @return 字符串
     */
    public static String dealResponse(Response<ResponseBody> response) {
        if (response == null) {
            return null;
        }
        ResponseBody errorBody = response.errorBody();
        String result = null;
        if (errorBody != null) {
            try {
                result = errorBody.string();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ResponseBody body = response.body();
        if (body == null) {
            okhttp3.Response rawResponse = response.raw();
            if (rawResponse != null) {
                LogUtils.e(TAG, "rawResponse() " + rawResponse.toString());
            }
            return result;
        }
        String jsonStr = null;
        try {
            jsonStr = body.string();
        } catch (Exception e) {
            LogUtils.e(TAG, e.getLocalizedMessage());
        }
        return jsonStr;
    }

    /**
     * 打印请求的接口信息
     *
     * @param call
     */
    private static void printCallInfo(Call<ResponseBody> call) {
        if (call == null) return;
        String logHttpHeaders = "";
        Request request = call.request();
        Headers headers = request.headers();
        if (headers != null) {
            for (int i = 0; i < headers.size(); i++) {
                logHttpHeaders += headers.name(i) + "=" + headers.value(i) + (i == headers.size() - 1 ? "" : ", ");
            }
        }
        String logHttpBody = "";
        RequestBody body = request.body();
        if (body != null && body instanceof FormBody) {
            FormBody formBody = (FormBody) body;
            for (int i = 0; i < formBody.size(); i++) {
                logHttpBody += formBody.name(i) + "=" + formBody.value(i) + (i == formBody.size() - 1 ? "" : "&");
            }
        }
        LogUtils.i(TAG, "url = " + request.url() + ", headers = " + logHttpHeaders + ", body = " + logHttpBody);
    }
}
